package com.example.xinli.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xinli.R;
import com.example.xinli.model.Comment;
import com.example.xinli.model.Post;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
    private List<Post> postList;
    private OnPostActionListener actionListener;
    private String currentUser;

    public interface OnPostActionListener {
        void onLikeClick(int position);
        void onCommentClick(int position);
        void onShareClick(int position);
        void onAddComment(int position, String commentContent);
    }

    public PostAdapter(List<Post> postList, String currentUser) {
        this.postList = postList;
        this.currentUser = currentUser;
    }

    public void setOnPostActionListener(OnPostActionListener listener) {
        this.actionListener = listener;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.bind(post);
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    class PostViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar, ivPostImage;
        TextView tvNickname, tvUsername, tvTime, tvContent, tvStats;
        ImageButton btnLike, btnComment, btnShare; // 修改为ImageButton
        LinearLayout layoutComments;
        RecyclerView recyclerComments;
        CommentAdapter commentAdapter;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvNickname = itemView.findViewById(R.id.tv_nickname);
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvContent = itemView.findViewById(R.id.tv_content);
            ivPostImage = itemView.findViewById(R.id.iv_post_image);
            btnLike = itemView.findViewById(R.id.btn_like);     // 修改为ImageButton
            btnComment = itemView.findViewById(R.id.btn_comment); // 修改为ImageButton
            btnShare = itemView.findViewById(R.id.btn_share);     // 修改为ImageButton
            tvStats = itemView.findViewById(R.id.tv_stats);
            layoutComments = itemView.findViewById(R.id.layout_comments);
            recyclerComments = itemView.findViewById(R.id.recycler_comments);
        }

        public void bind(Post post) {
            tvNickname.setText(post.getNickname());
            tvUsername.setText("@" + post.getUsername());
            tvContent.setText(post.getContent());

            // 格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
            tvTime.setText(sdf.format(new Date(post.getTimestamp())));

            // 设置图片显示
            if (post.getImageUrl() != null && !post.getImageUrl().isEmpty()) {
                ivPostImage.setVisibility(View.VISIBLE);
                // 这里可以使用图片加载库如Glide加载图片
                // 为了演示，我们使用本地文件加载
                loadPostImage(post.getImageUrl());
            } else {
                ivPostImage.setVisibility(View.GONE);
            }

            // 设置统计数据
            String statsText = post.getLikeCount() + " 点赞 · " + post.getComments().size() + " 评论";
            tvStats.setText(statsText);

            // 设置评论列表
            setupComments(post);

            // 设置按钮点击事件
            btnLike.setOnClickListener(v -> {
                if (actionListener != null) {
                    actionListener.onLikeClick(getAdapterPosition());
                }
            });

            btnComment.setOnClickListener(v -> {
                if (actionListener != null) {
                    actionListener.onCommentClick(getAdapterPosition());
                }
            });

            btnShare.setOnClickListener(v -> {
                if (actionListener != null) {
                    actionListener.onShareClick(getAdapterPosition());
                }
            });

            // 加载用户头像
            loadUserAvatar(post.getUsername());
        }

        private void setupComments(Post post) {
            if (post.getComments().size() > 0) {
                layoutComments.setVisibility(View.VISIBLE);
                commentAdapter = new CommentAdapter(post.getComments(), currentUser);
                recyclerComments.setLayoutManager(new LinearLayoutManager(itemView.getContext()));
                recyclerComments.setAdapter(commentAdapter);
            } else {
                layoutComments.setVisibility(View.GONE);
            }
        }

        private void loadUserAvatar(String username) {
            // 这里加载用户头像
            ivAvatar.setImageResource(R.drawable.ic_person);
        }

        private void loadPostImage(String imagePath) {
            // 加载本地图片
            try {
                File imgFile = new File(imagePath);
                if(imgFile.exists()){
                    Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                    ivPostImage.setImageBitmap(bitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ivPostImage.setImageResource(R.drawable.ic_image); // 默认图片
            }
        }
    }
}
